package problem37;

//37.解数独
//https://leetcode.cn/problems/sudoku-solver/description/
class Solution {
    boolean[][] row = new boolean[10][10];
    boolean[][] col = new boolean[10][10];
    boolean[][][] grid = new boolean[3][3][10];
    char[][] ret = new char[9][9];
    public void solveSudoku(char[][] board) {
        for(int i = 0; i<9; i++) {
            for(int j = 0; j<9; j++) {
                if(board[i][j] != '.') {
                    int x = board[i][j] - '0';
                    row[i][x] = col[j][x] = grid[i/3][j/3][x] = true;
                }
            }
        }
        dfs(board, 0, 0);
        for(int x = 0; x<9; x++) {
            for(int y = 0; y<9; y++) {
                board[x][y] = ret[x][y];
            }
        }
    }
    public void dfs(char[][] board, int i, int j) {
       if(j == 9) {
           i++;
           j = 0;
       }
       if(i == 9 && j == 0) {
            for(int x = 0; x<9; x++) {
                for(int y = 0; y<9; y++) {
                    ret[x][y] = board[x][y];
                }
            }
            return;
       }
       if(board[i][j] == '.') {
            //枚举每一个数字
            for (int x = 1; x <= 9; x++) {
                if(!row[i][x] && !col[j][x] && !grid[i/3][j/3][x]) {
                    row[i][x] = col[j][x] = grid[i/3][j/3][x] = true;
                    board[i][j] = (char)(x + '0');
                    dfs(board, i, j+1);
                    row[i][x] = col[j][x] = grid[i/3][j/3][x] = false;
                    board[i][j] = '.';
                }
            }
        }else {
            dfs(board, i, j+1);
        }
    }
}